package com.genesis.yunnanji.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.genesis.yunnanji.R;
import com.genesis.yunnanji.bean.RegisterBean;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;

import es.dmoral.toasty.Toasty;
import okhttp3.Call;



public class BindPhone extends BaseActivity {


    @ViewInject(R.id.tb_bindphone_toolbar)
    private Toolbar mToolbar;
    @ViewInject(R.id.tv_bind_title)
    private TextView tvTitle;
    @ViewInject(R.id.tv_bind_tips)
    private TextView tvTips;
    @ViewInject(R.id.tv_bind_first)
    private TextView tvFirst;
    @ViewInject(R.id.et_bind_first)
    private EditText etPhone;
    @ViewInject(R.id.tv_bind_getcode)
    private TextView tvGetCode;
    @ViewInject(R.id.bt_bind_comfirm)
    private Button btConfirm;
    @ViewInject(R.id.et_bind_second)
    private EditText etCode;
    private String smstoken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_bindphonemail);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvTitle.setText("绑定手机");
        tvTips.setText("绑定手机或换绑新手机");
        tvFirst.setText("手机号");
        etPhone.setHint("请输入手机号码");

    }

    @Override
    protected void setUpView() {
        tvGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCode();
            }
        });
        btConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(etPhone.getText().toString()) && !TextUtils.isEmpty(etCode.getText().toString())) {
                    Bind();
                }else{
                    Toasty.info(context, "请先完善资料！", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }


    private void getCode() {
        String token = genesisUtils.getMD5Str(genesisUtils.sortNum(etPhone.getText().toString() + GenesisApiConfig.TOKEN_STR));
        OkHttpUtils
                .post()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.BIND_PHONE_SMS)
                .addParams("mobile", etPhone.getText().toString())
                .addParams("token", token)
                .addParams("__apptoken__", genesisUtils.getAppToken())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        RegisterBean registerBean = gson.fromJson(response, RegisterBean.class);
                        if (registerBean.getStatus() == 200) {
                            smstoken = registerBean.getResult().getSmstoken();
                            Toasty.info(context, registerBean.getMessage(), Toast.LENGTH_SHORT).show();
                            Message message = handler.obtainMessage(1);     // Message
                            handler.sendMessageDelayed(message, 1000);
                        } else {
                            Toasty.error(context, registerBean.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    int recLen = 180;
    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    recLen--;
                    tvGetCode.setText(recLen + "S");

                    if (recLen > 0) {
                        Message message = handler.obtainMessage(1);
                        handler.sendMessageDelayed(message, 1000);      // send message
                        tvGetCode.setClickable(false);
                    } else {
                        tvGetCode.setClickable(true);
                        tvGetCode.setText("获取");
                    }
            }

            super.handleMessage(msg);
        }
    };

    public void Bind() {
        OkHttpUtils
                .post()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.BIND_PHONE)
                .addParams("mobile", etPhone.getText().toString())
                .addParams("smscode", genesisUtils.getMD5Str(etCode.getText().toString()))
                .addParams("smstoken", smstoken)
                .addParams("__apptoken__", genesisUtils.getAppToken())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);

                            if (jsonObject.optInt("status") == 200) {
                                Toasty.success(context, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                Toasty.error(context, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                });
    }
}
